from django.shortcuts import render, redirect
from models_user.models import *


# Create your views here.

def index(request):
    try:
        name = request.session['name']

        duty = request.session['duty']

    except KeyError:
        context = {'mes': '你没有登陆'}
        return render(request, 'login/login.html', context)
    else:
        user = User.objects.get(name=name)
        try:
            motto = Motto.objects.get(user_id=user.id)
        except Motto.DoesNotExist:
            subtool = '由于我们系统是落后于实际情况，此功能用于添加某房间内的具体资产情况；由于我们系统是落后于实际情况，' \
                      '此功能用于添加某房间内的具体资产情况；由于我们系统是落后于实际情况，此功能用于添加某房间内的具体资产情况' \
                      '由于我们系统是落后于实际情况，此功能用于添加某房间内的具体资产情况；由于我们系统是落后于实际情况，' \
                      '此功能用于添加某房间内的具体资产情况；由于我们系统是落后于实际情况，此功能用于添加某房间内的具体资产情况'
            context = {'name': name, 'duty': duty, 'motto': '虽然过去不能改变，未来可以', 'subtool': subtool}
            return render(request, 'index/index.html', context)
        else:
            text = motto.text
            context = {'name': name, 'duty': duty, 'motto': text}
            return render(request, 'index/index.html', context)

        # if motto:
        #     if request.method == 'POST':
        #         info = request.POST['m']
        #         context = {'name': name, 'duty': duty, 'motto': info}
        #         return render(request, 'index/index.html', context)
        #     else:
        #         list = []
        #         for i in motto:
        #             global m
        #             m = i.text
        #             list.append(m)
        #         context = {'name': name, 'duty': duty, 'motto': list}
        #         return render(request, 'index/index3.html', context)
        # else:


def logout(request):
    request.session.delete()
    context = {'mes': '注销成功'}

    return render(request, 'login/login.html', context)


def submit(request):
    if request.method == 'GET':
        name = request.session['name']
        user = User.objects.get(name=name)
        try:
            motto = Motto.objects.get(user_id=user.id)
        except Motto.DoesNotExist:
            context = {'name': name, 'motto': '虽然过去不能改变，未来可以'}
            return render(request, 'index/alter.html', context)
        else:
            m = motto.text
            context = {'name': name, 'motto': m}
            return render(request, 'index/alter.html', context)
    elif request.method == 'POST':
        m = request.POST.get('motto')
        name = request.session['name']
        user = User.objects.get(name=name)
        try:
            a = Motto.objects.get(user_id=user.id)
        except Motto.DoesNotExist:
            Motto.objects.create(text=m, user_id=user.id)
            return redirect('index:index')
        else:
            a.text = m
            a.save()
            return redirect('index:index')



